/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TrabViewPanel.java
 *
 * Created on 29/11/2011, 22:26:52
 */

package proj5labbd.graphics.trabalho;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

public class TrabViewPanel extends OperationPanel {

    private ArrayList<String> fields;
    /** Creates new form TrabViewPanel */
    public TrabViewPanel(TrabFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        fields = new ArrayList<String>();
        TrabAction act = new TrabAction();
        jbtView.addActionListener(act);
        jchkDepartamento.addItemListener(act);
        jchkFuncionario.addItemListener(act);
        jchkInicio.addItemListener(act);
        jchkFim.addItemListener(act);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam1 = new javax.swing.JPanel();
        jlbDepartamento1 = new javax.swing.JLabel();
        jtxtDepartamento = new javax.swing.JTextField();
        jlbInicio1 = new javax.swing.JLabel();
        jlbFim1 = new javax.swing.JLabel();
        jlbFuncionario1 = new javax.swing.JLabel();
        jtxtFuncionario = new javax.swing.JTextField();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jpnField = new javax.swing.JPanel();
        jchkDepartamento = new javax.swing.JCheckBox();
        jchkFuncionario = new javax.swing.JCheckBox();
        jchkInicio = new javax.swing.JCheckBox();
        jchkFim = new javax.swing.JCheckBox();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbView = new javax.swing.JTable();
        jbtView = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Visualização"));

        jpnParam1.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da busca"));

        jlbDepartamento1.setText("Departamento");

        jlbInicio1.setText("Início");

        jlbFim1.setText("Fim");

        jlbFuncionario1.setText("Funcionário");

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParam1Layout = new javax.swing.GroupLayout(jpnParam1);
        jpnParam1.setLayout(jpnParam1Layout);
        jpnParam1Layout.setHorizontalGroup(
            jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParam1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jtxtFuncionario, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jtxtDepartamento, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                    .addComponent(jlbFuncionario1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jlbDepartamento1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpnParam1Layout.createSequentialGroup()
                        .addComponent(jlbInicio1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(152, 152, 152))
                    .addGroup(jpnParam1Layout.createSequentialGroup()
                        .addComponent(jlbFim1)
                        .addContainerGap(98, Short.MAX_VALUE))
                    .addGroup(jpnParam1Layout.createSequentialGroup()
                        .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jftxtFim, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jftxtIni, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        jpnParam1Layout.setVerticalGroup(
            jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParam1Layout.createSequentialGroup()
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbDepartamento1)
                    .addComponent(jlbInicio1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtDepartamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbFuncionario1)
                    .addComponent(jlbFim1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParam1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(25, Short.MAX_VALUE))
        );

        jpnField.setBorder(javax.swing.BorderFactory.createTitledBorder("Campos a selecionar"));

        jchkDepartamento.setText("Departamento");

        jchkFuncionario.setText("Funcionário");

        jchkInicio.setText("Início");

        jchkFim.setText("Fim");

        javax.swing.GroupLayout jpnFieldLayout = new javax.swing.GroupLayout(jpnField);
        jpnField.setLayout(jpnFieldLayout);
        jpnFieldLayout.setHorizontalGroup(
            jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnFieldLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jchkDepartamento)
                    .addComponent(jchkFuncionario)
                    .addComponent(jchkInicio)
                    .addComponent(jchkFim))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        jpnFieldLayout.setVerticalGroup(
            jpnFieldLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnFieldLayout.createSequentialGroup()
                .addComponent(jchkDepartamento)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkFuncionario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkInicio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jchkFim)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jtbView.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbView);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 628, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 198, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jbtView.setText("Visualizar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jpnParam1, javax.swing.GroupLayout.PREFERRED_SIZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jpnField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addContainerGap())
                    .addComponent(jbtView, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jpnField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jpnParam1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(24, 24, 24)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                .addComponent(jbtView))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtView;
    private javax.swing.JCheckBox jchkDepartamento;
    private javax.swing.JCheckBox jchkFim;
    private javax.swing.JCheckBox jchkFuncionario;
    private javax.swing.JCheckBox jchkInicio;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbDepartamento1;
    private javax.swing.JLabel jlbFim1;
    private javax.swing.JLabel jlbFuncionario1;
    private javax.swing.JLabel jlbInicio1;
    private javax.swing.JPanel jpnField;
    private javax.swing.JPanel jpnParam1;
    private javax.swing.JTable jtbView;
    private javax.swing.JTextField jtxtDepartamento;
    private javax.swing.JTextField jtxtFuncionario;
    // End of variables declaration//GEN-END:variables

    class TrabAction implements ActionListener, ItemListener {
        
         /*
         * Método para receber os valores dos atributos que serão usados na seleção
         * para exibição da tabela "trabalho", além da escolha de quais campos serão exibidos.
         */
         public void actionPerformed(ActionEvent e) {

                String [] titles = {"ID do departamento","ID do funcionário","Data de início","Data de fim"};
                ArrayList<String> tables = new ArrayList<String>();
                tables.add("trabalho");
                boolean joinDept = false;
                boolean joinFunc = false;

                try {
                    ArrayList<String> param = new ArrayList<String>();
                    String s[][];

                    if (jtxtDepartamento.getText().trim().compareTo("") != 0) {
                        tables.add("departamento");
                        param.add("trabalho.idDe=departamento.idDe");
                        param.add("UPPER(departamento.nomeDe)=UPPER('"+jtxtDepartamento.getText()+"')"); 
                        joinDept = true;
                    }
                    if (jtxtFuncionario.getText().trim().compareTo("") != 0) {
                        tables.add("funcionario");
                         param.add("trabalho.idFu=funcionario.idFu");
                         param.add("UPPER(funcionario.nomeCompletoDe)=UPPER('"+jtxtFuncionario.getText()+"')");   
                         joinFunc = true;
                    }
                    if (jftxtIni.getText().compareTo("  -  -    ") != 0) {
                        param.add("trabalho.dataInicioTr="
                                + "TO_DATE('"+jftxtIni.getText()+"','DD-MM-YYYY')");
                    }
                    if (jftxtFim.getText().compareTo("  -  -    ") != 0) {
                        param.add("trabalho.dataInicioTr="
                                + "TO_DATE('"+jftxtFim.getText()+"','DD-MM-YYYY')");
                    }

                    if (param.size() > 0 ) {

                            if (fields.size() > 0) {

                                if (jchkDepartamento.isSelected() && !joinDept) {
                                        param.add("departamento.idDe=trabalho.idDe"); 
                                        tables.add("departamento");  
                                }
                                if (jchkFuncionario.isSelected() && !joinFunc) {
                                    param.add("funcionario.idFu=trabalho.idFu");
                                    tables.add("funcionario");
                                }

                                String[] fieldArray = new String[fields.size()];
                                String[] tableArray = new String[tables.size()];
                                String[] paramArray = new String[param.size()];
                                
                                param.toArray(paramArray);
                                tables.toArray(tableArray);
                                fields.toArray(fieldArray);
                                s = dbInterface.view(fieldArray, paramArray, tableArray);
                                jtbView.setModel(
                                        new DefaultTableModel(s,fieldArray)
                                        );
                            }
                            else {
                                String[] tableArray = new String[tables.size()];
                                String[] paramArray = new String[param.size()];
                                tables.toArray(tableArray);
                                param.toArray(paramArray);
                                s = dbInterface.view(null, paramArray, tableArray);
                                jtbView.setModel(
                                        new DefaultTableModel(s,titles)
                                        );
                            }


                     }

                    else {
                         if (fields.size() > 0) {
                             
                                if (jchkDepartamento.isSelected() && !joinDept) {
                                        param.add("departamento.idDe=trabalho.idDe"); 
                                        tables.add("departamento");  
                                }
                                if (jchkFuncionario.isSelected() && !joinFunc) {
                                    param.add("funcionario.idFu=trabalho.idFu");
                                    tables.add("funcionario");
                                }

                                String[] fieldArray = new String[fields.size()];
                                String[] tableArray = new String[tables.size()];
                                String[] paramArray = new String[param.size()];
                                tables.toArray(tableArray);
                                fields.toArray(fieldArray);
                                param.toArray(paramArray);
                                s = dbInterface.view(fieldArray, paramArray, tableArray);
                                jtbView.setModel(
                                        new DefaultTableModel(s,fieldArray)
                                        );
                            }
                        else {
                            String[] tableArray = new String[tables.size()];
                            tables.toArray(tableArray);
                            s = dbInterface.view(null, null, tableArray);
                            jtbView.setModel(
                                            new DefaultTableModel(s,titles)
                                            );
                         }
                    }
                }
                catch (SQLException ex) {
                    frame.printException(ex);
                    JOptionPane.showMessageDialog(null, "Erro ao resgatar as tuplas desejadas.");
                } finally {
                    joinDept = false;
                    joinFunc = false;
                }

            }
             
             /*
              * Método para controlar a seleção das checkbox
              */
             public void itemStateChanged(ItemEvent ie) {
                if ( ie.getStateChange() == ItemEvent.SELECTED ) {
                    if (ie.getSource() == jchkDepartamento) {
                        fields.add("departamento.nomeDe");
                    }
                    if (ie.getSource() == jchkFuncionario) {
                        fields.add("funcionario.nomeCompletoFu");
                    }
                    if (ie.getSource() == jchkInicio) {
                        fields.add("trabalho.dataInicioTr");
                    }
                    if (ie.getSource() == jchkFim) {
                        fields.add("trabalho.dataFimTr");
                    }
                }
                if ( ie.getStateChange() == ItemEvent.DESELECTED ) {
                    if (ie.getSource() == jchkDepartamento) {
                        fields.remove("departamento.nomeDe");
                    }
                    if (ie.getSource() == jchkFuncionario) {
                        fields.remove("funcionario.nomeCompletoFu");
                    }
                    if (ie.getSource() == jchkInicio) {
                        fields.remove("trabalho.dataInicioTr");
                    }
                    if (ie.getSource() == jchkFim) {
                        fields.remove("trabalho.dataFimTr");
                    }
                }
            }

        }

}
